package middleware

import (
	"AiBus/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

func ChecKToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println(err)
				utils.Fail(c, 401, errors.New("服务异常").Error())
			}
			c.Abort()
			return
		}()
		tokenString := c.Request.Header.Get("Authorization")
		if tokenString == "" {
			utils.Fail(c, 401, errors.New("token解析失败").Error())
			c.Abort()
			return
		}
		if strings.Split(tokenString, " ")[0] != "Bearer" {
			utils.Fail(c, 401, errors.New("token格式错误").Error())
			c.Abort()
			return

		}
		//	校验token合法性
		token, err := utils.ParseToken(strings.Split(tokenString, " ")[1])
		if err != nil {
			utils.Fail(c, 401, "token解析错误")
			c.Abort()
			return
		}
		// 判断过期时间
		if time.Now().Unix() > token.ExpiresAt.Unix() {
			utils.Fail(c, 401, "token授权过期")
			c.Abort()
			return
		} else {

			c.Set("open_id", token.OpenID.OpenID)
			c.Next()
		}
	}
}
